package com.newcapec.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.newcapec.entity.ResponseJson;
import com.newcapec.entity.UserInfo;
import com.newcapec.service.UserInfoService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    @GetMapping("/findById/{userId}")
    public ResponseJson<UserInfo> findById(@PathVariable("userId") Integer userId){
        UserInfo userInfo = userInfoService.findById(userId);
        ResponseJson<UserInfo> result = new ResponseJson<>();
        if(userInfo == null){
            result.setCode(500);
            result.setMsg("未找到数据");
        }else{
            result.setCode(200);
            result.setMsg("找到数据");
            result.setData(userInfo);
        }

        return result;
    }

    @GetMapping("/login/{userName}/{userPwd}/{verifyCode}")
    public ResponseJson<UserInfo> login(@PathVariable("userName")String userName
            , @PathVariable("userPwd")String userPwd
            , @PathVariable("verifyCode")String verifyCode, HttpServletRequest request){
        //验证验证码
        HttpSession session = request.getSession();
        String googleVerifyCode = (String) request.getSession().getAttribute("googleVerifyCode");
        UserInfo userInfo = null;
        if(!verifyCode.equals(googleVerifyCode)){
            ResponseJson result = new ResponseJson();
            result.setCode(500);
            result.setMsg("验证码不一致");
            return result;
        }
        userInfo = userInfoService.login(userName,userPwd);
        if(userInfo == null){
            ResponseJson result = new ResponseJson();
            result.setCode(500);
            result.setMsg("用户名密码错误");
            return result;
        }

        ResponseJson result = new ResponseJson();
        result.setCode(200);
        result.setMsg("登录成功");
        return result;
    }

    @GetMapping("/findByPage")
    public ResponseJson<Map> findByPage(@RequestParam("pageNumber") Integer pageNum,
                                        @RequestParam("pageSize") Integer pageSize,UserInfo userInfo){
        Map<String,Object> data = userInfoService.selectByPage(pageNum,pageSize,userInfo);
        ResponseJson<Map> result = new ResponseJson<>();
        if(data != null){
            result.setCode(200);
            result.setMsg("查询成功");
            result.setData(data);
        }else {
            result.setCode(500);
            result.setMsg("查询失败");
        }
        return result;
    }

    @GetMapping("/exportExcel")
    public void exportExcel(UserInfo userInfo, HttpServletResponse response) throws IOException {
        response.setContentType("application/octet-stream; charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("用户信息.xls", "UTF-8"));
        List<UserInfo> list = userInfoService.select(userInfo);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("用户信息", "测试", "用户数据"),
                UserInfo.class, list);
        OutputStream out = response.getOutputStream();
        workbook.write(out);
        out.flush();
        out.close();

    }

    @PostMapping("/importExcel")
    public ResponseJson importExcel(HttpServletRequest request){
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        ResponseJson result = new ResponseJson();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(false);
            try {
                List<UserInfo> list = ExcelImportUtil.importExcel(file.getInputStream(), UserInfo.class, params);
                boolean flag = userInfoService.saveBatch(list);
                if(flag){
                    result.setCode(200);
                    result.setMsg("导入成功");
                }else{
                    result.setCode(500);
                    result.setMsg("导入失败");
                }

            } catch (Exception e) {
                e.printStackTrace();
                result.setCode(500);
                result.setMsg("导入失败");

            }
        }
        return result;
    }

    @PostMapping("/insert")
    public ResponseJson insert(UserInfo userInfo){
        ResponseJson result = new ResponseJson();
        int count = userInfoService.insert(userInfo);
        if(count == 0){
            result.setCode(500);
            result.setMsg("插入失败");
        }else if(count == 1){
            result.setCode(200);
            result.setMsg("插入成功");
        }
        return result;
    }


    @DeleteMapping("/batchDelete")
    public ResponseJson batchDelete(Integer[] userIds){
        ResponseJson result = new ResponseJson();
        if(userInfoService.batchDelete(userIds)>0){
            result.setCode(200);
            result.setMsg("删除成功");
        }else{
            result.setCode(500);
            result.setMsg("删除失败");
        }
        return result;
    }

    @PutMapping("/updateUser")
    public ResponseJson updateUser(UserInfo userInfo){
        ResponseJson result = new ResponseJson();
        if(userInfoService.updateUser(userInfo)>0){
            result.setCode(200);
            result.setMsg("更新成功");
        }else{
            result.setCode(500);
            result.setMsg("更新失败");
        }
        return result;
    }
}
